package com.bigcms.interceptor;

import com.bigcms.utils.JWTUtils;
import com.bigcms.utils.JsonData;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class Loginceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)){
            sendJsonMessage(response,JsonData.Return(300,"参数错误"));
        }
        Claims claims =JWTUtils.checkJWT(token);
        if(claims==null){
            sendJsonMessage(response,JsonData.Return(300,"token失效请重新登陆"));
        }

        Integer id = (Integer) claims.get("id");
        String name = (String) claims.get("nick_name");

        request.setAttribute("uid", id);
        request.setAttribute("nick_name", name);

        return true;

    }

    public static void sendJsonMessage(HttpServletResponse response,Object obj) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(objectMapper.writeValueAsString(obj));
        writer.close();
        response.flushBuffer();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
